package com.yuandian.customer.perception.controller;

import com.yuandian.api.customer_perception.po.*;
import com.yuandian.api.customer_perception.vo.AlarmVo;
import com.yuandian.api.customer_perception.vo.ImportanceOperator;
import com.yuandian.api.customer_perception.vo.LastAlarmVo;
import com.yuandian.bpm.common.core.util.R;
import com.yuandian.customer.perception.service.IImportanceOperatorService;
import com.yuandian.utils.PageDataInfo;
import com.yuandian.utils.YDateUtil;
import com.yuandian.utils.poi.ExcelTitleUtils;
import com.yuandian.utils.poi.ExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.text.ParseException;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * 重点用户
 *
 * @Author wangpeiyang
 * @Date 2021/5/17 16:58
 */
@Slf4j
@RestController
@RequestMapping("/business/importanceOperator/monitoring")
public class ImportanceOperatorController {

    @Autowired
    private IImportanceOperatorService importanceOperatorService;

    /**
     * 获取重点用户中最新告警信息
     *
     * @param params
     * @return
     */
    @RequestMapping("/queryLastAlarm")
    public R<Object> queryLastAlarm(LastAlarmParams params) {
        if (params == null) {
            return R.failed("请求参数不能为空");
        }
        if (params.getSystemId() == null || 0 == params.getSystemId()) {
            return R.failed("请求参数：系统不能为空");
        }
        //设置查询时间为当天
        params.setStartTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd 00:00:00")));
        params.setEndTime(LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd 23:59:59")));
        //查询重点人员信息
        List<ImportanceOperator> operatorList = importanceOperatorService.queryImportanceOperatorList();
        List<String> operatorIds = importanceOperatorService.getImportanceOperatorIds(operatorList);
        if (CollectionUtils.isEmpty(operatorIds)) { return R.ok(new LastAlarmVo()); }

        params.setOperatorIds(operatorIds);
        LastAlarmVo lastAlarm = importanceOperatorService.queryLastAlarm(params);
        //回填重点人员信息
        backFillLastAlarm(lastAlarm, operatorList);
        return lastAlarm != null ? R.ok(lastAlarm) : R.ok(new LastAlarmVo());
    }

    /**
     * 重点用户-业务系统健康度
     */
    @RequestMapping("/queryBusinessHealthRate")
    public R<Object> queryBusinessHealthRate(BusinessHealthRateParams params) {
        if (params == null) {
            return R.failed("请求参数不能为空");
        }
        if (params.getSystemId() == null || 0 == params.getSystemId()) {
            return R.failed("请求参数：系统不能为空");
        }
        R<Object> result = importanceOperatorService.queryBusinessHealthRate(params);
        return result;
    }

    /**
     * 重点用户-告警趋势
     */
    @RequestMapping("/queryAlarmTrendList")
    public R<Object> queryAlarmTrendList(AlarmTrendParams params) {
        if (params == null) {
            return R.failed("请求参数不能为空");
        }
        if (params.getSystemId() == null || 0 == params.getSystemId()) {
            return R.failed("请求参数：系统不能为空");
        }
        //设置查询开始时间,结束时间:查当前时间往前推11.5个小时,如果当前时间<11:30,则开始时间取00:00
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime benchMark = LocalDateTime.of(LocalDate.now(), LocalTime.of(11, 30));
        if (now.isBefore(benchMark)) {
            //当前是11:30前
            params.setStartTime(LocalDate.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd 00:00:00")));
        } else {
            //11:30后
            LocalDateTime start = now.minusHours(11).minusMinutes(30);
            params.setStartTime(start.format(DateTimeFormatter.ofPattern(YDateUtil.YYYY_MM_DD_HH_MM_SS)));
        }
        params.setEndTime(now.format(DateTimeFormatter.ofPattern(YDateUtil.YYYY_MM_DD_HH_MM_SS)));
		return importanceOperatorService.queryAlarmTrendList(params);

    }

    /**
     * 重点用户-告警统计
     *
     * @param params
     * @return
     */
    @RequestMapping("/queryAlarmList")
    public R<PageDataInfo> queryAlarmList(@RequestBody AlarmParams params) {
        if (params == null) { return R.failed("请求参数不能为空"); }

        if (params.getPageNum() == 0) { params.setPageNum(1); }
        if (params.getPageSize() == 0) { params.setPageSize(10); }
        //查询系统返回码（5）、业务返回码（6）、提示语告警类型（7）
        params.setAlarmIndicatorIds(Arrays.asList(5, 6, 7));
        return importanceOperatorService.queryAlarmList(params);
    }

    /**
     * 重点用户-告警统计下载
     */
    @RequestMapping("/queryAlarmListExport")
    public void queryAlarmListExport(@RequestBody AlarmParams params, HttpServletResponse response) throws ParseException, IOException {
        //查询系统返回码（5）、业务返回码（6）、提示语告警类型（7）
        params.setAlarmIndicatorIds(Arrays.asList(5, 6, 7));
        List<AlarmVo> list = new ArrayList<>();
        try {
            list = (List<AlarmVo>) importanceOperatorService.queryAlarmList(params).getData().getData();
        } catch (Exception e) {
            log.error("所选时间表不存在!但表格需要正常导出.");
        }


        String title = "重点用户实时告警列表";
        String fileName = title + System.currentTimeMillis();

        List<String> titleParams = new ArrayList<>();
        titleParams.add(title);
        String formTitleName = ExcelTitleUtils.formTitleName(titleParams,params.getStartTime(),params.getEndTime());

        List<List<String>> headList = new ArrayList<>();
        List<String> titleList = Arrays.asList("序号", "用户ID", "姓名", "部门", "告警类型", "所属业务", "所属步骤", "登录IP"
                , "告警时间", "告警描述");
        titleList.forEach(s -> {
            List<String> childHeadList = new ArrayList<>();
            childHeadList.add(formTitleName);
            childHeadList.add(s);
            headList.add(childHeadList);
        });
        //回填序号
        int index = 1;
        for (AlarmVo alarmVo : list) {
            alarmVo.setId(index++);
        }
        ExcelUtil.writeExcel(AlarmVo.class, "", "重点用户实时告警列表", list, headList, 20, response);
    }


    /**
     * 重点用户实时使用情况列表
     *
     * @return
     */
    @GetMapping("/realTimeUsage/{systemId}")
    public R<Object> importanceOperatorRealTimeUsage(@PathVariable Integer systemId) {
        return importanceOperatorService.importanceOperatorRealTimeUsage(systemId);
    }

    /**
     * 重点用户实时使用情况列表
     *
     * @return
     */
    @GetMapping("/realTimeUsage")
    public R<Object> importanceOperatorRealTimeUsage() {
        return importanceOperatorService.importanceOperatorRealTimeUsage(null);
    }


    /**
     * 用户操作轨迹列表
     *
     * @param params 查询参数
     * @return
     */
    @PostMapping("/operateTrajectory")
    public R<Object> operateTrajectory(@Validated @RequestBody OperateTrajectoryParams params) {
        return importanceOperatorService.operateTrajectory(params);
    }

    /**
     * 用户操作轨迹散点图
     *
     * @param params 查询参数
     * @return 用户操作轨迹散点图数据
     */
    @PostMapping("/operateTrajectoryTrend")
    public R<Object> operateTrajectoryTrend(@Validated @RequestBody OperateTrajectoryParams params) throws ParseException {
        return importanceOperatorService.operateAllTrajectory(params);
    }

	/**
	 * 查询重点用户列表
	 *
	 * @return 通用返回对象
	 */
	@PostMapping("/queryImportanceOperatorList")
	public R<PageDataInfo> queryImportanceOperatorList(@RequestBody ImportanceOperatorParams params) {
		return importanceOperatorService.findByPager(params);
	}

    /**
     * 实时告警姓名下拉框接口
     * @return 实时告警重点用户姓名数据
     */
    @PostMapping("/operatorNameSearchOption")
    public R<Object> operatorNameSearchOption() {
        return R.ok(importanceOperatorService.operatorNameSearchOption());
    }

    /**
     * 实时告警用户名下拉框接口
     * @return 实时告警用户名下拉框接口
     */
    @PostMapping("/operatorIdSearchOption")
    public R<Object> operatorIdSearchOption() {
        return R.ok(importanceOperatorService.operatorIdSearchOption());
    }

    /**
     * 查询用户当天操作的业务code
     */
    @GetMapping("/getBusinessByOperaorId/{systemId}/{id}")
    public R<Object> getBusinessByOperatorId(@NotNull(message = "系统id不能为空") @PathVariable Integer systemId,
                                         @NotNull(message = "用户id不能为空") @PathVariable String id) {
        return importanceOperatorService.getBusinessByOperatorId(systemId, id);
    }

    /**
     * 回填最新告警中重点用户信息
     */
    private void backFillLastAlarm(LastAlarmVo lastAlarm, List<ImportanceOperator> list) {
        if (lastAlarm != null && lastAlarm.getOperatorId() != null && !CollectionUtils.isEmpty(list)) {
            for (ImportanceOperator operator : list) {
                if (lastAlarm.getOperatorId().equals(operator.getOperatorId())) {
                    lastAlarm.setName(operator.getName());
                    lastAlarm.setDepartment(operator.getDepartment());
                    break;
                }
            }
        }
    }


}
